<template>
  <div class="che-jian-container">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="action-buttons">
        <el-button type="primary" size="default" @click="openAddDialog(null)">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="danger" size="default" :disabled="!selectedRows.length" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
          <el-button @click="EXcel">
          导出
        </el-button>
      </div>
      
      <div class="search-tools">
        <el-button type="text" size="small" @click="refreshData" title="刷新">
          <el-icon><RefreshLeft /></el-icon>
        </el-button>
        <el-button type="text" size="small" @click="showAdvancedSearch = !showAdvancedSearch" title="搜索">
          <el-icon><Search /></el-icon>
        </el-button>
        <el-button type="text" size="small" title="视图切换">
          <el-icon><Grid /></el-icon>
        </el-button>
        <el-button type="text" size="small" title="设置">
          <el-icon><Setting /></el-icon>
        </el-button>
      </div>
    </div>
    <transition name="fade">
      <div class="selected-info" v-if="selectedRows.length > 0">
        <span class="selected-text">已选{{ selectedRows.length }}项</span>
        <el-button type="text" size="small" @click="cancelSelection">
          取消选择
        </el-button>
      </div>
    </transition>

    <!-- 表格 -->
    <el-table 
      ref="tableRef"
      :data="tableData" 
      style="width: 100%" 
      border
      @selection-change="handleSelectionChange"
      highlight-current-row
    >
     <el-table-column type="selection" width="55" />
      <el-table-column prop="workshopcoding" label="车间编号" width="120">
        <template #header>
          <div class="column-header-with-search">
            <span>车间编号</span>
            <el-icon @click="showColumnSearch.workshopcoding = !showColumnSearch.workshopcoding" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.workshopcoding" class="column-search">
            <el-input 
              v-model="searchForm.workshopcoding" 
              placeholder="请输入车间编号" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="workshopname" label="车间名称" width="120">
        <template #header>
          <div class="column-header-with-search">
            <span>车间名称</span>
            <el-icon @click="showColumnSearch.workshopname = !showColumnSearch.workshopname" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.workshopname" class="column-search">
            <el-input 
              v-model="searchForm.workshopname" 
              placeholder="请输入车间名称" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="describe" label="描述" width="120">
        <template #header>
          <div class="column-header-with-search">
            <span>描述</span>
            <el-icon @click="showColumnSearch.describe = !showColumnSearch.describe" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.describe" class="column-search">
            <el-input 
              v-model="searchForm.describe" 
              placeholder="请输入描述" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createName" label="创建人" width="120">
        <template #header>
          <div class="column-header-with-search">
            <span>创建人</span>
            <el-icon @click="showColumnSearch.createName = !showColumnSearch.createName" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.createName" class="column-search">
            <el-input 
              v-model="searchForm.createName" 
              placeholder="请输入创建人" 
              size="small" 
              clearable 
              style="width: 100%"
              @keydown.enter="handleSearch"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #header>
          <div class="column-header-with-search">
            <span>创建时间</span>
            <el-icon @click="showColumnSearch.createTime = !showColumnSearch.createTime" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.createTime" class="column-search">
            <el-date-picker
              v-model="searchForm.createTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              style="width: 100%"
              @change="handleSearch"
            />
          </div>
        </template>
        <template #default="scope">
          {{ scope.row.createTime ? moment(scope.row.createTime).format("YYYY年MM月DD日") : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180">
        <template #header>
          <div class="column-header-with-search">
            <span>修改时间</span>
            <el-icon @click="showColumnSearch.updateTime = !showColumnSearch.updateTime" class="search-icon">
              <Search />
            </el-icon>
          </div>
          <div v-if="showColumnSearch.updateTime" class="column-search">
            <el-date-picker
              v-model="searchForm.updateTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              style="width: 100%"
              @change="handleSearch"
            />
          </div>
        </template>
        <template #default="scope">
          {{ scope.row.updateTime ? moment(scope.row.updateTime).format("YYYY年MM月DD日") : '' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openAddDialog(scope.row)" class="operation-btn">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope.row)" class="operation-btn">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <span class="total-text">共{{Page.totalCount}}条数据</span>
      <el-pagination
        v-model:current-page="Page.Pageindex"
        v-model:page-size="Page.PageSize"
        :page-sizes="[5,10,15,20]"
        layout="prev, pager, next, jumper, sizes"
        :total="Page.totalCount"
        prev-text="上一页"
        next-text="下一页"
      />
    </div>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="addDialogVisible.is"
      :title="addDialogVisible.title"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <el-form :model="formData"  add label-width="80px">
        <el-form-item label="编码" >
          <el-input
            v-model="formData.workshopcoding"
            clearable
          />
        </el-form-item>
        <el-form-item label="名称" >
          <el-input
            v-model="formData.workshopname"
            clearable
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.describe"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible.is = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElTable, ElMessageBox, ElForm, ElMessage } from 'element-plus';
import {
  RefreshLeft, Search, Grid, ArrowRight, ArrowLeft,
  Plus, Download, Delete, Edit, Setting
} from '@element-plus/icons-vue';
import {APIs } from '@/Http/http';
import moment from 'moment';
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref([
]);
const showAdvancedSearch = ref(false);
const searchForm = reactive({
  "workshopcoding": "",
  "workshopname": "",
  "describe": "",
  "createName": "",
  "createTime": "",
  "updateTime":""
});

const showColumnSearch = reactive({
  workshopcoding: false,
  workshopname: false,
  describe: false,
  createName: false,
  createTime: false,
  updateTime: false
});

// 加载状态


// 选中的行
const selectedRows = ref<any[]>([]);

// 新增弹窗
const addDialogVisible = reactive({
  title:"",
  is:false
});
const formData = reactive({
  "workshopcoding": "",
  "workshopname": "",
  "describe": "",
});


// 处理选择变化
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
  console.log(selectedRows.value);
};
const cancelSelection = () => {
  tableRef.value?.clearSelection();
};
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除【${row.workshopname}】吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/DeleCheJian",row).then(res=>{
      if(res.data.code==100)
    {
       ElMessage.success("删除成功")
       Data();
    }
    })
  })
};

const openAddDialog = (row:any) => {
  addDialogVisible.is = true;
  if(row==null)
{
  
    formData.describe=""
    formData.workshopcoding=""
    formData.workshopname=""
    addDialogVisible.title="新增"
}
else
{
    addDialogVisible.title="编辑"
   Object.assign(formData,row)
}
};
onMounted(()=>{
  Data();
})
const Page=reactive({
  Pageindex:1,
  PageSize:5,
  total:0,
  totalCount:0
})
const Data=()=>{
  APIs.get("/api/Read/ListCheJian",{params:{
    Pageindex:Page.Pageindex,
    PageSize:Page.PageSize
  }}).then(res=>{
    tableData.value=res.data.data.data
    Page.total=res.data.data.total
    Page.totalCount=res.data.data.totalCount
    
  })
}

// 处理新增确认
const handleAddConfirm = () => {
  if(addDialogVisible.title=="新增")
{
 APIs.post("/api/Write/AddCheJian",formData).then(res=>{
    if(res.data.code==100)
   {
      ElMessage.success("添加成功")
      addDialogVisible.is=false
      Data();
   }
   })
}
else 
{
   APIs.post("/api/Write/UpdateChejian",formData).then(res=>{
    if(res.data.code==100)
   {
      ElMessage.success("修改成功")
      addDialogVisible.is=false
      Data();
   }
   })
}
  
};

const EXcel=()=>{
  // 设置请求头，确保能够处理二进制文件
  const config = {
    responseType: 'blob' as const,
    headers: {
      'Content-Type': 'application/json'
    }
  };
  
  // 调用导出接口
  APIs.get("/api/Read/DowCheJian", config).then(res=>{
    // 创建Blob对象
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
    
    // 创建临时URL
    const url = window.URL.createObjectURL(blob);
    
    // 创建临时a标签用于下载
    const link = document.createElement('a');
    link.href = url;
    
    // 设置文件名
    const timestamp = new Date().getTime();
    link.download = `车间信息_${timestamp}.xlsx`;
    
    // 模拟点击下载
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    // 显示成功提示
    ElMessage.success("导出成功");
  }).catch(error => {
    // 显示错误提示
    ElMessage.error("导出失败，请重试");
    console.error("导出错误:", error);
  });
}

// 刷新数据
const refreshData = () => {
  setTimeout(() => {
  }, 500);
};

watch(Page,()=>{
  Data();
})
const getSelectedRowsArray = () => {
  return selectedRows.value.map(row => ({
    id: row.workid,
  }));
};

// 实现批量删除功能
const handleBatchDelete = () => {
  const selectedIds = getSelectedRowsArray();
  
  // 仅提取ID值，不进行任何过滤
  const requestData = {
    Ids: selectedIds.map(item => item.id)
  };
  
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}个车间吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/PLDeleCheJian", requestData).then(res=>{
      if(res.data.code==100) {
        ElMessage.success("批量删除成功");
        // 添加短暂延迟以确保界面更新的平滑性
        setTimeout(() => {
          Data();  // 刷新数据
          cancelSelection();  // 取消选择
        }, 100);
      }
    })
  });
};
const handleSearch = () => {
  Data();
  setTimeout(() => {
  }, 500);
};
</script>

<style scoped>
.che-jian-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

/* 顶部操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: box-shadow 0.3s ease;
}

.action-bar:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.search-tools {
  display: flex;
  gap: 4px;
}

.search-tools .el-button {
  transition: all 0.3s ease;
}

.search-tools .el-button:hover {
  color: #1890ff;
  background-color: #e6f7ff;
}

/* 高级搜索区域 */
.advanced-search {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 16px 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
}

.search-form .el-form-item {
  margin-right: 20px;
}

/* 已选状态提示 */
.selected-info {
  padding: 10px 20px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.selected-text {
  color: #1890ff;
  font-weight: 500;
}

/* 表格样式 */
.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.el-table__header-wrapper th {
  background-color: #fafafa !important;
  font-weight: 500;
}

.el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

.el-table__body tr.current-row > td {
  background-color: #e6f7ff !important;
}

/* 操作按钮样式 */
.operation-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
}

.operation-btn:hover {
  transform: translateY(-1px);
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 16px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.total-text {
  color: #666;
  font-size: 14px;
}

/* 弹窗样式 */
.el-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.el-dialog__header {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.el-dialog__body {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
}

.el-input__inner:focus,
.el-textarea__inner:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 分配属性弹窗样式 */
.assign-attribute-container {
  display: flex;
  gap: 16px;
  height: 480px;
}

.available-attributes,
.selected-attributes {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.selected-header {
  margin-bottom: 10px;
  font-weight: 500;
  color: #333;
  padding: 4px 0;
}

.transfer-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
}

.transfer-buttons .el-button {
  min-width: 40px;
  padding: 12px 0;
  transition: all 0.3s ease;
}

.btn-hover:hover {
  transform: scale(1.1);
}

.pagination-small {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 加载动画优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.9);
}

.el-loading-spinner {
  top: 50%;
  margin-top: -25px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .assign-attribute-container {
    flex-direction: column;
    height: auto;
  }
  
  .transfer-buttons {
    flex-direction: row;
    justify-content: center;
    margin: 10px 0;
  }
}

@media (max-width: 768px) {
  .che-jian-container {
    padding: 10px;
  }
  
  .action-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .search-tools {
    justify-content: center;
  }
}

/* 列头搜索样式 */
.column-header-with-search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 5px;
}

.search-icon {
  cursor: pointer;
  color: #909399;
  transition: color 0.2s;
}

.search-icon:hover {
  color: #409eff;
}

.column-search {
  padding: 5px 0;
}
</style>
